/**************************************************************
WinFilter version 0.8
http://www.winfilter.20m.com
akundert@hotmail.com

Filter type: Band Pass
Filter model: Butterworth
Filter order: 2
Sampling Frequency: 32 KHz
Fc1 and Fc2 Frequencies: 5.100000 KHz and 7.200000 KHz
Coefficents Quantization: 16-bit

Z domain Zeros
z = -1.000000 + j 0.000000
z = -1.000000 + j 0.000000
z = 1.000000 + j 0.000000
z = 1.000000 + j 0.000000

Z domain Poles
z = 0.188092 + j -0.836229
z = 0.188092 + j 0.836229
z = 0.434040 + j -0.756058
z = 0.434040 + j 0.756058
***************************************************************/
#define NCoef 4
#define DCgain 16

typedef signed short __int16;
typedef signed long __int32;

__int16 iir6(__int16 NewSample) {
    __int16 ACoef[NCoef+1] = {
        13558,
            0,
        -27117,
            0,
        13558
    };

    __int16 BCoef[NCoef+1] = {
        16384,
        -20386,
        29839,
        -15133,
         9148
    };

    static __int32 y[NCoef+1]; //output samples
    //Warning!!!!!! This variable should be signed (input sample width + Coefs width + 4 )-bit width to avoid saturation.

    static __int16 x[NCoef+1]; //input samples
    int n;

    //shift the old samples
    for(n=NCoef; n>0; n--) {
       x[n] = x[n-1];
       y[n] = y[n-1];
    }

    //Calculate the new output
    x[0] = NewSample;
    y[0] = ACoef[0] * x[0];
    for(n=1; n<=NCoef; n++)
        y[0] += ACoef[n] * x[n] - BCoef[n] * y[n];

    y[0] /= BCoef[0];
    
    return y[0] / DCgain;
}
